package btree4j.template;

import btree4j.BTree;
import btree4j.BTreeException;
import btree4j.BTreeIndex;
import btree4j.Value;
import btree4j.utils.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class TemplateIndexManager {
    //private Map<Long, BTreeIndex> templateIndexes = new HashMap<>();   //主键索引
    private Map<Long, Map<String, BTreeIndex>> templateIndexes = new HashMap<>(); // 改为双层Map
    private File dataDir;
    private TemplateManager templateManager; // 添加对模板管理器的引用

    public TemplateIndexManager(File dataDir, TemplateManager templateManager) {
        this.dataDir = dataDir;
        this.templateManager = templateManager;
    }

    public void createTemplateIndex(long templateId, String columnName) throws IOException, BTreeException {
        String indexFileName = templateId + "_" + columnName + ".idx";
        File indexFile = new File(dataDir, indexFileName);

        BTreeIndex index = new BTreeIndex(indexFile);
        index.init(false);

        Map<String, BTreeIndex> columnIndexes = templateIndexes.computeIfAbsent(templateId, k -> new HashMap<>());
        columnIndexes.put(columnName, index);
    }

    public BTreeIndex getTemplateIndex(long templateId, String columnName) {
        Map<String, BTreeIndex> columnIndexes = templateIndexes.get(templateId);
        return columnIndexes != null ? columnIndexes.get(columnName) : null;
    }

    public void removeTemplateIndex(long templateId, String columnName) throws IOException, BTreeException, InterruptedException {
        Map<String, BTreeIndex> columnIndexes = templateIndexes.get(templateId);
        if (columnIndexes == null) return;
        BTreeIndex index = columnIndexes.remove(columnName);
        if (index != null) {
            index.close(); // 确保索引文件被正确关闭
            System.out.println("检查是否关闭："+index.close());
            File indexFile = new File(dataDir, templateId + "_" + columnName + ".idx");
            System.out.println("Attempting to delete index file: " + indexFile);
            if (indexFile.exists()) {
                if (indexFile.isDirectory()) {
                    FileUtils.cleanDirectory(indexFile);
                }
                try {
                    Files.delete(indexFile.toPath());
                } catch (IOException e) {
                    System.err.println("Failed to delete index file: " + e.getMessage());
                }
            }
        }
    }

    // 修改原有方法，增加columnName参数
    public void addDataToIndex(long templateId, String columnName, Value key, Value value) throws BTreeException {
        BTreeIndex index = getTemplateIndex(templateId, columnName);
        if (index != null) {
            index.addValue(key, value);
            index.flush();
        }
    }

    // 更新数据时处理二级索引
    public void updateIndex(long templateId, String columnName, Value oldKey, Value newKey, Value primaryKey) throws BTreeException {
        BTreeIndex index = getTemplateIndex(templateId, columnName);
        if (index != null) {
            if (oldKey != null) {
                index.removeValue(oldKey);
            }
            index.addValue(newKey, primaryKey);
            index.flush();
        }
    }

    public void removeDataFromIndex(long templateId, String columnName, Value key) throws BTreeException {
        BTreeIndex index = getTemplateIndex(templateId, columnName);
        if (index != null) {
            index.remove(key);
            index.flush();
        }
    }

    public void removeDataFromIndex(long templateId, String columnName, Value indexKey, long primaryKey) throws BTreeException {
        BTreeIndex index = getTemplateIndex(templateId, columnName);
        if (index != null) {
            index.removeValue(indexKey, primaryKey); // 确保BTreeIndex支持此方法
            index.flush();
        }
    }


    public Value getDataFromIndex(long templateId, String columnName, Value key) throws BTreeException {
        BTreeIndex index = getTemplateIndex(templateId, columnName);
        return index != null ? index.getValue(key) : null;
    }


    public String getPrimaryKeyColumn(long templateId) throws BTreeException, IOException {
        Template template = templateManager.getTemplate(templateId);
        if (template == null) {
            throw new IllegalArgumentException("Template with ID " + templateId + " not found");
        }

        for (Column column : template.getColumns()) {
            if (column.isPrimaryKey()) {
                return column.getName();
            }
        }

        throw new IllegalArgumentException("Template with ID " + templateId + " has no primary key column");
    }


    public void close() throws IOException, BTreeException {
        for (Map<String, BTreeIndex> columnIndexes : templateIndexes.values()) {
            for (BTreeIndex index : columnIndexes.values()) {
                index.close();
            }
        }
    }
}